<template>
  <van-pull-refresh v-model="refreshing" @refresh="onLoad('refresh')">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        class="listItem"
        v-for="(item, index) in listData"
        :key="index"
        @click="cardClick(item)"
      >
        <slot :row="item" />
      </van-cell>
    </van-list>
  </van-pull-refresh>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const emit = defineEmits(["getData", "cardClick"]);
const props = defineProps({
  // 表格列
  listData: {
    type: Array,
    default: () => [],
  },
  total: {
    type: Number,
    default: 0,
  },
  pageSize: {
    type: Number,
    default: 10,
  },
});
const listData = ref([]); //列表数据
const refreshing = ref(false); //下拉刷新
const loading = ref(false); //上拉加载
const finished = ref(false); //是否加载完成
const queryParams = reactive({
  //查询参数
  pageNum: 1,
  pageSize: 0,
});
const pages = ref(0); //总页数

const onLoad = (type: string = "") => {
  //加载列表
  if (type === "refresh") {
    finished.value = false;
    loading.value = true;
  }

  if (refreshing.value || type === "refresh") {
    // pages.value = 0;
    queryParams.pageNum = 1;
    listData.value = [];
    refreshing.value = false;
  }

  if (type !== "refresh") {
    if (queryParams.pageNum >= pages.value) return;
    queryParams.pageNum++;
  }
  getList();
};
const getList = async () => {
  //获取列表数据
  loading.value = true;
  await emit("getData", queryParams);
  try {
    let data = props.listData || [];
    if (queryParams.pageNum == 1) {
      listData.value = data;
    } else {
      listData.value = listData.value.concat(data);
    }
    if (queryParams.pageNum == pages.value || pages.value == 0) {
      finished.value = true;
    }
  } catch (error) {
    finished.value = true;
  }
  loading.value = false;
};
const cardClick = (item) => {
  //点击卡片跳转详情
  emit("cardClick", item);
};
onMounted(() => {
  listData.value = props.listData;
  queryParams.pageSize = props.pageSize;
  pages.value = Math.ceil(props.total / props.pageSize);
});
</script>

<style scoped lang="less">
.listItem {
  margin-bottom: 10px;
  background: #fff;
  border-radius: 5px;
  padding: 0;
}
</style>
